//
//  KLMThemeManager.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/19.
//

import UIKit

// 定义主题协议
protocol Theme {
    var viewBgColor: UIColor { get }
    var textColor: UIColor { get }
    var btnBgColor: UIColor { get }
    var btnTextColor: UIColor { get }
    var textFieldBgColor: UIColor { get }
    var cellBgColor: UIColor { get }
    var navBarBgColor: UIColor { get }
    var navBarTextColor: UIColor { get }
    var themeColor: UIColor { get } // 主题色
}

// 浅色主题
struct LightTheme: Theme {
    let viewBgColor: UIColor = .white
    let textColor: UIColor = .black
    let btnBgColor: UIColor = appMainThemeColor // 主题色相关的蓝色
    let btnTextColor: UIColor = .white
    let textFieldBgColor: UIColor = .black
    let cellBgColor: UIColor = .black
    let navBarBgColor: UIColor = .clear
    let navBarTextColor: UIColor = .black
    let themeColor: UIColor = appMainThemeColor
}

// 深色主题
struct DarkTheme: Theme {
    let viewBgColor: UIColor = .black
    let textColor: UIColor = .white
    let btnBgColor: UIColor = rgb(100, 149, 237)// 主题色相关的蓝色变种
    let btnTextColor: UIColor = .black
    let textFieldBgColor: UIColor = UIColor(white: 0.15, alpha: 1)
    let cellBgColor: UIColor = .white
    let navBarBgColor: UIColor = .systemGray2
    let navBarTextColor: UIColor = .white
    let themeColor: UIColor = rgb(100, 149, 237)
}

// 主题管理器
class KLMThemeManager {
    static let shared = KLMThemeManager()
    private(set) var currentTheme: Theme
    
    private init() {
        // 根据系统的外观模式设置初始主题
        if #available(iOS 13.0, *) {
            let userInterfaceStyle = UITraitCollection.current.userInterfaceStyle
            currentTheme = userInterfaceStyle == .dark ? DarkTheme() : LightTheme()
        } else {
            currentTheme = LightTheme()
        }
        // 监听系统外观模式变化
        if #available(iOS 13.0, *) {
            NotificationCenter.default.addObserver(self, selector: #selector(systemAppearanceChanged), name: UIScene.willEnterForegroundNotification, object: nil)
        }
    }
    
    // 切换主题的方法
    func changeTheme(to theme: Theme) {
        currentTheme = theme
        NotificationCenter.default.post(name: .themeChanged, object: nil)
    }
    
    // 自动跟随系统模式
    @objc private func systemAppearanceChanged() {
        if #available(iOS 13.0, *) {
            let userInterfaceStyle = UITraitCollection.current.userInterfaceStyle
            let newTheme: Theme = userInterfaceStyle == .dark ? DarkTheme() : LightTheme()
            if type(of: currentTheme) != type(of: newTheme) {
                changeTheme(to: newTheme)
            }
        }
    }
}


